package com.homework.action;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.homework.dao.CourseUtil;
import com.homework.doamin.Course;
import com.homework.util.HomeworkUtil;
import com.jspsmart.upload.SmartUpload;

public class PictureUpload extends Action {
	private ServletConfig config=null;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		this.getServlet().init(config);
		int count=0;
		CourseUtil courseUtil=new CourseUtil();
		HomeworkUtil homeworkUtil=new HomeworkUtil();
		SmartUpload su=new SmartUpload();
		su.initialize(config, request, response);
		try{
			su.setAllowedFilesList("jpeg,jpg,tiff,raw,bmp,gif,png");
			su.setTotalMaxFileSize(30000000);
			su.upload();
			Course course=courseUtil.getCourseByAcronym(su.getRequest().getParameter("course_acronym"));
			String ps=su.getRequest().getParameter("ps");
			courseUtil.add2Homework(course.getCourseId(),ps);
			String newFileName=null;
			for(int i=0;i<su.getFiles().getCount();i++){
				com.jspsmart.upload.File myFile=su.getFiles().getFile(i);
				newFileName=homeworkUtil.getRandomFileName()+"."+myFile.getFileExt();
				courseUtil.add2Picture(course.getCourseId(),newFileName);
				//myFile.saveAs(request.getServletContext().getRealPath("")+"\\pictures\\"+newFileName);
				myFile.saveAs("saestor://pictures/"+newFileName);
				//myFile.saveAs(request.getServletContext().getContextPath())
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return mapping.findForward("successupload");
		
	}
	
	
}
